import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 选择组件
///
/// [ItemType.select]
///
/// 结合 KqFormEntity 使用
///
/// @author 周卓
///
class KqSelectItemView extends StatefulWidget {
  final KqFormEntity entity;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqFormEntity entity)? customRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqFormEntity entity)? customBottomView;

  /// 选择控件点击回调
  final Function(KqFormEntity entity)? onTap;

  /// 自定义或选择控件的标题点击回调
  final Function(KqFormEntity entity)? onTitleTap;

  const KqSelectItemView(
      {Key? key,
      required this.entity,
      this.onTap,
      this.onTitleTap,
      this.customLeftView,
      this.customRightView,
      this.customBottomView})
      : super(key: key);

  @override
  KqSelectItemViewState createState() => KqSelectItemViewState();
}

class KqSelectItemViewState extends State<KqSelectItemView> {
  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 获取1行高度
  double measureTextHeight(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.height;
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var titleTextStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize:
                KqThemeManager.instance.getConfig().formConfig.titleFontSize ??
                    16.sp,
            color: widget.entity.titleColor ?? KqThemeColors.text26);
    // 一行标题的高度
    var titleOneLineHeight =
        measureTextHeight(widget.entity.title, textStyle: titleTextStyle);
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgDialog;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          KqInkWell(
            onTap: widget.entity.forceOnTap || widget.entity.isEditable()
                ? () {
                    TextFiledUtil.clearFocus(context);
                    if (widget.entity.onTap != null) {
                      widget.entity.onTap!(widget.entity);
                    }
                    if (widget.onTap != null) {
                      widget.onTap!(widget.entity);
                    }
                  }
                : null,
            backgroundColor: bgColor,
            child: Container(
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      24.r),
              decoration: widget.entity.showFocusBorder
                  ? BoxDecoration(
                      color: bgColor,
                      border: Border.all(width: 1, color: KqThemeColors.bgBlue))
                  : null,
              child: Row(
                crossAxisAlignment: widget.entity.multiline
                    ? CrossAxisAlignment.baseline
                    : CrossAxisAlignment.center,
                textBaseline:
                    widget.entity.multiline ? TextBaseline.alphabetic : null,
                children: <Widget>[
                  KqInkWell(
                    onTap: widget.entity.onTitleTap != null ||
                            widget.onTitleTap != null
                        ? () {
                            widget.entity.onTitleTap?.call(widget.entity);
                            widget.onTitleTap?.call(widget.entity);
                          }
                        : null,
                    child: Container(
                      padding: EdgeInsets.only(
                          right: widget.entity.titleRightMargin ?? (widget.entity.title.isNotEmpty ? 10.r : 0),
                          top: widget.entity.paddingVertical ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingVertical ??
                              24.r,
                          bottom: widget.entity.paddingVertical ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingVertical ??
                              24.r),
                      child: Row(
                        children: <Widget>[
                          /// 是否必填
                          Container(
                            alignment: Alignment.centerRight,
                            width: widget.entity.paddingHorizontal ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingHorizontal ??
                                24.r,
                            padding: EdgeInsets.only(right: 2.r),
                            child: Text(
                              "∗",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .mustInputFontSize ??
                                      24.sp,
                                  color: widget.entity.mustInput
                                      ? KqThemeColors.textRed
                                      : KqThemeColors.bgTransparent),
                            ),
                          ),

                          /// 标题
                          if (widget.entity.title.isNotEmpty)
                            LimitedBox(
                              maxWidth: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .titleMaxWidth ??
                                  200.r,
                              child: Text(
                                widget.entity.title,
                                style: titleTextStyle,
                              ),
                            )
                        ],
                      ),
                    ),
                  ),

                  /// 右侧文字
                  Expanded(
                    child: Row(
                      children: [
                        /// 左边自定义控件
                        /// 自定义布局，来自实体类
                        widget.entity.customLeftView != null
                            ? widget.entity.customLeftView!(widget.entity)
                            : Container(),

                        /// 自定义布局，来自控件
                        widget.customLeftView != null
                            ? widget.customLeftView!(widget.entity)
                            : Container(),

                        // 为了和UI规范的标题和内容之间距离40
                        SizedBox(
                          width: 30.r,
                          height: 1.r,
                        ),

                        Expanded(
                          child: Padding(
                            padding: EdgeInsets.symmetric(
                                vertical: widget.entity.paddingVertical ??
                                    KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .paddingVertical ??
                                    24.r),
                            child: Text(
                              widget.entity.valueForShow ??
                                  (widget.entity.hint ?? ''),
                              textAlign: TextAlign.right,
                              overflow: widget.entity.overflow ??
                                  (!widget.entity.multiline
                                      ? TextOverflow.ellipsis
                                      : null),
                              maxLines: widget.entity.multiline
                                  ? widget.entity.maxLines
                                  : 1,
                              style: TextStyle(
                                color: widget.entity.valueForShow != null
                                    ? widget.entity.contentColor ??
                                        KqThemeColors.text59
                                    : KqThemeColors.textBF,
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .contentFontSize ??
                                    16.sp,
                              ),
                            ),
                          ),
                        ),
                        Text(
                          widget.entity.unit ?? '',
                          textAlign: TextAlign.right,
                          style: TextStyle(
                            color: widget.entity.contentColor ??
                                KqThemeColors.text59,
                            fontSize: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .contentFontSize ??
                                16.sp,
                          ),
                        )
                      ],
                    ),
                  ),

                  /// 自定义布局
                  widget.entity.customRightView != null
                      ? widget.entity.customRightView!(widget.entity)
                      : Container(),

                  /// 自定义布局
                  widget.customRightView != null
                      ? widget.customRightView!(widget.entity)
                      : Container(),

                  /// 右侧箭头
                  Visibility(
                      visible: widget.entity.isEditable(),
                      child: Container(
                          padding: EdgeInsets.only(left: 4.r),
                          margin: EdgeInsets.only(
                              top: widget.entity.multiline
                                  ? (widget.entity.paddingVertical ??
                                      KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .paddingVertical ??
                                      24.r)
                                  : 0),
                          width: titleOneLineHeight,
                          height: titleOneLineHeight,
                          alignment: Alignment.center,
                          child: Image.asset(
                            KqImages.commonIcJiantouRight16,
                            width: 24.r,
                            height: 24.r,
                            fit: BoxFit.fill,
                            package: KqGlobal.packageName,
                          ))),
                ],
              ),
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider, child: const KqDivider())
        ],
      ),
    );
  }
}
